﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 环形UI布局
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Layout/Radial Layout Group")]
    public sealed class RadialLayoutGroup : LayoutGroup
    {
        /// <summary>
        /// 各个UI距离
        /// </summary>
        [SerializeField]
        private float distance;

        [Range(0f, 360f)]
        [SerializeField]
        private float minAngle;
        [Range(0f, 360f)]
        [SerializeField]
        private float maxAngle;
        [Range(0f, 360f)]
        [SerializeField]
        private float startAngle;

        private void UpdateLayout()
        {
            this.m_Tracker.Clear();
            if (transform.childCount == 0) return;
            float avgAngle = (this.maxAngle - this.minAngle) / transform.childCount;
            for(int i = 0; i < transform.childCount; i++)
            {
                var _rectTransform = transform.GetChild(i) as RectTransform;
                float angle = this.startAngle + i * avgAngle;
                Vector3 pos = new Vector3(Mathf.Cos(angle * 0.017453292f), Mathf.Sin(angle * 0.017453292f), 0f);
                _rectTransform.localPosition = pos * this.distance;
                DrivenTransformProperties drivenTransformProperties = DrivenTransformProperties.Pivot 
                    | DrivenTransformProperties.Anchors 
                    | DrivenTransformProperties.AnchoredPosition;
                this.m_Tracker.Add(this, _rectTransform, drivenTransformProperties);
                _rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
                _rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
                _rectTransform.pivot = new Vector2(0.5f, 0.5f);
            }
        }


        public override void SetLayoutHorizontal()
        {
            this.UpdateLayout();
        }


        public override void SetLayoutVertical()
        {
            this.UpdateLayout();
        }

        public override void CalculateLayoutInputVertical()
        {
            
        }

#if UNITY_EDITOR
        protected override void OnValidate()
        {
            base.OnValidate();
            this.UpdateLayout();
        }

#endif

    }
}

